import requests
import json
import ast

def add(*args):
    return sum(args)

def subtract(a, b):
    return a - b

def multiply(*args):
    result = 1
    for x in args:
        result *= x
    return result

def equal(a, b):
    return a == b

def notequal(a, b):
    return a != b

def greater(a, b):
    return a > b

def less(a, b):
    return a < b

def not_(a):
    return not a

def contains(a, b):
    return b in a

def strip(a):
    return a.strip()

def append(lst, item):
    return lst + [item]

def dictget(d, key, default=None):
    return d.get(key, default)

def condition(expr, context):
    # 安全地在 context 下 eval 表达式
    return eval(expr, {}, context)

def from_json(value):
    """
    通用 JSON 字符串转对象 filter/函数，兼容单引号伪JSON
    """
    try:
        if isinstance(value, (dict, list)):
            return value
        return json.loads(value)
    except Exception:
        try:
            # 尝试用 ast.literal_eval 解析单引号字典/列表
            return ast.literal_eval(value)
        except Exception:
            return value

# 硅基流动大模型 API

def gen(prompt, stop=None, max_tokens=8192, temperature=0.8, model="Qwen/Qwen3-8B", **kwargs):
    api_key = "sk-kqethriccfwpztqswbdkmtnfaisjomvkimwhfxbfeyswcdyx"
    url = "https://api.siliconflow.cn/v1/messages"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stream": False
    }
    if stop:
        data["stop"] = stop
    print("[gen] 请求地址:", url)
    print("[gen] headers:", headers)
    print("[gen] data:", data)
    resp = requests.post(url, headers=headers, json=data, timeout=60)
    print("[gen] 响应状态码:", resp.status_code)
    print("[gen] 响应内容:", resp.text)
    resp.raise_for_status()
    content = resp.json().get("content")
    if isinstance(content, list) and content and "text" in content[0]:
        return content[0]["text"].strip()
    else:
        return str(content)

def gen_stream(prompt, stop=None, max_tokens=8192, temperature=0.8, model="Qwen/Qwen3-8B", **kwargs):
    api_key = "sk-kqethriccfwpztqswbdkmtnfaisjomvkimwhfxbfeyswcdyx"
    url = "https://api.siliconflow.cn/v1/messages"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stream": True
    }
    if stop:
        data["stop"] = stop
    print("[gen_stream] 请求地址:", url)
    print("[gen_stream] headers:", headers)
    print("[gen_stream] data:", data)
    resp = requests.post(url, headers=headers, json=data, stream=True, timeout=60)
    print("[gen_stream] 响应状态码:", resp.status_code)
    resp.raise_for_status()
    for line in resp.iter_lines():
        if line:
            if line.startswith(b'data: '):
                content = line[6:].decode('utf-8')
                if content == '[DONE]':
                    break
                import json
                delta = json.loads(content)
                # 流式内容格式：{"content": [{"type": "text", "text": "..."}]}
                if "content" in delta and isinstance(delta["content"], list):
                    for part in delta["content"]:
                        if part.get("type") == "text" and "text" in part:
                            print("[gen_stream] 响应内容:", part["text"])
                            yield part["text"] 